const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const { userInfo } = event.data
  const res = await db.collection('user').add({
    data: { ...userInfo, openid, updateTime: new Date() }
  })
  const id = res._id
  return db.collection('user').doc(id).get()
}